package com.zoroki.hmusic.service.impl;

import com.zoroki.hmusic.constant.MessageConstant;
import com.zoroki.hmusic.entity.Lyrics;
import com.zoroki.hmusic.mapper.LyricsMapper;
import com.zoroki.hmusic.service.ILyricsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoroki.hmusic.util.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zoroki
 * @since 2023-05-10
 */
@Service
@Slf4j
public class LyricsServiceImpl extends ServiceImpl<LyricsMapper, Lyrics> implements ILyricsService {

    @Autowired
    private LyricsMapper lyricsMapper;

    @Override
    public int addLyrics(Lyrics lyrics) {
        int insert = lyricsMapper.insert(lyrics);
        if (insert > 0) {
            log.info("lyrics添加成功");
            return lyrics.getId();
        }
        log.error("lyrics添加失败");
        return -1;
    }

    @Override
    public Lyrics updateLyrics(Lyrics lyrics, String url) {
        //1.删除七牛云文件
        String urlOld = lyrics.getUrl();
        String fileName = urlOld.substring(urlOld.lastIndexOf("/")+1);
        try{
            QiniuUtil.deleteFile(MessageConstant.FOLDER_LRC + fileName);
        }catch (Exception e){
            log.error(e.getMessage());
            return null;
        }

        //2.更新url
        lyrics.setUrl(url);
        int update = lyricsMapper.updateById(lyrics);

        if (update > 0) {
            log.info("lyrics更新成功");
            return lyrics;
        }
        log.error("lyrics更新失败");
        return null;
    }

    @Override
    public Lyrics getLyricsById(int id) {
        return lyricsMapper.selectById(id);
    }

    @Override
    public int deleteLyricsById(int id) {
        //删除七牛云中的歌词文件
        Lyrics lyrics = lyricsMapper.selectById(id);
        String url = lyrics.getUrl();
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        QiniuUtil.deleteFile(MessageConstant.FOLDER_LRC + fileName);
        return lyricsMapper.deleteById(id);
    }
}
